import 'dart:async';

import 'package:aliplayer_widget/aliplayer_widget_lib.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:hktk_app/dao/course_dao.dart';
import 'package:hktk_app/decoration/chapter_expansion_tile.dart';
import 'package:hktk_app/exception/dao_exception.dart';
import 'package:hktk_app/model/course/video_info_model.dart';
import 'package:hktk_app/model/data_model.dart';
import 'package:hktk_app/model/course/course_chapter_model.dart';
import 'package:hktk_app/util/data_util.dart';
import 'package:hktk_app/util/event_bus_util.dart';
import 'package:hktk_app/util/font_util.dart';
import 'package:hktk_app/util/toast_util.dart';
import 'package:hktk_app/util/view_util.dart';
import 'package:hktk_app/widget/course/course_leaf_widget.dart';
import 'package:hktk_app/widget/subject/chapter_indent_widget.dart';
import 'package:hktk_app/widget/subject/chapter_show_qnum_widget.dart';
// import 'package:hktk_app/widget/subject/chapter_indent_widget.dart';
// import 'package:hktk_app/widget/subject/chapter_show_qnum_widget.dart';

/// 章节可展开组件
class RecommendExpandableWidget extends StatefulWidget {
  /// 对应数据
  final CourseChapterModel model;

  /// 栏目id
  final String columnId;

  /// 是否免费，true：免费，false：不免费
  final bool free;

  /// 是否在第一位时打开对应数据
  final bool opening;

  /// 是否是第一次打开
  final bool init;

  /// 是否是课程详情进入，默认为false，true：是，false：否
  final bool courseDetail;

  const RecommendExpandableWidget({
    super.key,
    required this.model,
    required this.columnId,
    required this.free,
    required this.opening,
    required this.init,
    this.courseDetail = false,
  });

  @override
  State<RecommendExpandableWidget> createState() =>
      _RecommendExpandableWidgetState();
}

class _RecommendExpandableWidgetState extends State<RecommendExpandableWidget> {
  late BuildContext _context;

  /// 控制器
  late ChapterExpansionTileController _controller;

  /// 是否处于打开模式
  late bool _isOpenIt;

  /// 子组件数据，懒加载·
  late List<CourseChapterModel> _childList;

  /// 视频信息集合
  late List<VideoInfoModel> _videoInfoList;

  /// 数据是否加载完成
  late bool _dataInit;

  /// 监听课程页面刷新方法
  late StreamSubscription<EventCourseRefresh> _eventRefresh;
  late StreamSubscription<PlayerEvent> _eventPlayer;

  @override
  void initState() {
    super.initState();

    _controller = ChapterExpansionTileController();
    _isOpenIt = false;
    _childList = [];
    _videoInfoList = [];
    _dataInit = false;
    // todo 监听播放完成事件，
    _eventPlayer=eventBus.on<PlayerEvent>().listen((value){
      if(value.playState==FlutterAvpdef.completion){
        // _videoInfoList
        for (var element in _videoInfoList) {
          if(element.id==value.videoId){
            element.fs=true;
            break;
          }
        }
        setState(() {

        });

      }
    });

    // 是否打开，打开方法
    if (widget.opening) {
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
        _controller.expand();
      });
    }

    // 监听方法-监听课程页面是否刷新
    _eventRefresh = eventBus.on<EventCourseRefresh>().listen((event) {
     if (_isOpenIt) {
        _handleRefresh();
      }
    });
  }

  @override
  void dispose() {
    super.dispose();

    _eventPlayer.cancel();
    _eventRefresh.cancel();
  }

  @override
  Widget build(BuildContext context) {

    _context = context;
    return ChapterExpansionTile(
      controller: _controller,
      // 监听是否打开
      onExpansionChanged: _onChangedFun,
      // 父组件显示样式
      title: _title(),
      // 是否显示分割线
      dividerDisplayTime: DividerDisplayTime.never,
      // 子集组件
      children: _subItems(),
    );
  }

  /// title 组件显示，展开集合标题
  _title() {
    return Column(
      children: [

        _titleTopItem(),
        _bottomItem(),
      ],
    );
  }

  /// 标题显示
  _titleTopItem() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Row(
          children: [
            SvgPicture.asset(
              _isOpenIt
                  ? "images/home/course_zk.svg"
                  : "images/home/course_bh.svg",
              width: 24,
              height: 24,
            ),
            hiSpace(width: 16),
            Text(
              widget.model.name!,
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: FontUtil.fontBlack1(20, fontWeight: FontWeight.w500),
            ),
          ],
        ),
        Icon(
          _isOpenIt ? Icons.expand_less : Icons.expand_more,
          size: 32,
        ),
      ],
    );
  }

  /// 底部显示组件
  _bottomItem() {
    return ChapterIndentWidget(
      indent: 17,
      paddingLeft: 17,
      height: 32,
      child: ChapterShowQnumWidget(
        qCount: widget.model.videoNum ?? 0,
        num: widget.model.watchNum ?? 0,
        showQuestion: true,
        tipsSuffix: "",
      ),
    );

  }

  /// 子集组件
  _subItems() {
    List<Widget> list = [];
    list.add(_indentItem(height: 32));
    if (widget.model.leaf == true) {
      // 最后一级，显示视频信息
      _setListByVideoInfo(list: list);
    } else {
      // 不是最后一级，显示子级章节
      _setListByChildChapter(list: list);
    }
    list.add(_indentItem(height: 32));
    return list;
  }

  /// 根据视频信息加载对应组件
  _setListByVideoInfo({required List<Widget> list}) {
    if (_videoInfoList.isNotEmpty) {
      for (int i = 0; i < _videoInfoList.length; i++) {
        VideoInfoModel infoModel = _videoInfoList[i];
        list.add(_indentItem(
          child: CourseLeafWidget(
            infoModel: infoModel,
            columnId: widget.columnId,
            free: widget.free,
            chapterId: widget.model.id!,
            chapterName: widget.model.name!,
            courseDetail: widget.courseDetail,
          ),
        ));
        // 添加间距
        if (i != _videoInfoList.length - 1) {
          list.add(_indentItem(height: 30));
        }
      }
    }
  }

  /// 根据子级章节获取对应组件
  _setListByChildChapter({required List<Widget> list}) {
    if (_childList.isNotEmpty) {
      for (int i = 0; i < _childList.length; i++) {
        CourseChapterModel model = _childList[i];
        list.add(_indentItem(
          child: RecommendExpandableWidget(
            model: model,
            columnId: widget.columnId,
            free: widget.free,
            opening: i == 0 && widget.opening && widget.init,
            init: widget.init,
            courseDetail: widget.courseDetail,
          ),
        ));
      }
    }
  }

  /// 缩进组件显示
  _indentItem({
    double? height,
    Widget? child,
  }) {
    return ChapterIndentWidget(
      indent: 17,
      paddingLeft: 17,
      height: height,
      child: child,
    );

  }

  /// 监听是否打开方法
  void _onChangedFun(bool value) {
    if (value && !_dataInit) {
      // 开启加载框
      ToastUtil.loadingBoxShow(_context);
      // 加载数据
      _childrenInit().then((Map<String, dynamic> map) {
        // 结束加载框
        ToastUtil.loadingBoxRemove();
        if (map["suc"]) {
          _isOpenIt = value;
          setState(() {});
        } else {
          // 折叠，不打开
          _controller.collapse();
          ToastUtil.show(context: _context, msg: map["msg"]);
        }
      });
    } else {
      setState(() {
        _isOpenIt = value;
      });
    }
  }

  /// 加载相关数据方法
  Future<Map<String, dynamic>> _childrenInit() async {
    Map<String, dynamic> map = {};
    try {
      DataModel dataModel = dataUtilComm.dataModel;
      // 判断该章节是否是最后一级
      if (widget.model.leaf == true) {
        // 最后一级，获取对应视频信息
        _videoInfoList = await CourseDao.listByChapter(
          industryCode: dataModel.industryId,
          examId: dataModel.examId,
          categoryId: dataModel.categoryId,
          columnId: widget.columnId,
          chapterId: widget.model.id!,
        );
      } else {
        // 获取对应子集数据
        _childList = await CourseDao.childChapterVideo(
          industryCode: dataModel.industryId,
          examId: dataModel.examId,
          categoryId: dataModel.categoryId,
          columnId: widget.columnId,
          pId: widget.model.id!,
        );
      }

      _dataInit = true;
      map["suc"] = true;
    } catch (e) {
      map = {"suc": false, "msg": "未知错误，请重试"};
      if (e is DaoException) {
        map["msg"] = e.msg;
      }
    }
    return map;
  }

  /// 处理刷新方法
  void _handleRefresh() {
     dataUtilComm.chapterRefreshState.addRefreshState(id: widget.model.id!);
    // 发送请求
    _childrenInit().then((Map<String, dynamic> map) {

      dataUtilComm.chapterRefreshState.finishRefreshState(id: widget.model.id!);
      if (!map["suc"]) {
        ToastUtil.show(context: _context, msg: map["msg"]);
      }
    });

  }
}
